package com.controller;

import com.dto.excution.ListExcution;
import com.dto.in.RegisterInfo;
import com.entity.LoginInfo;
import com.enums.ListEnum;
import com.service.LoginService;
import com.util.AESDecodeUtils;
import com.util.UUIDUtil;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by Administrator on 2019/1/2 0002.
 */
@RequestMapping("/login")
@RestController
public class LoginController {
    @Autowired
    private LoginService service;


    @PostMapping(value = "/test")
    @ResponseBody
    public String test(){
        return "凌英jj小项目已就绪！";
    }

    @ApiOperation(value = "修改手机号")
    @PostMapping(value = "/updatePhone")
    @ResponseBody
    public ListExcution<Void> updatePhone(Integer userId, String phone,Integer type){
        int success=service.updatePhone(userId,phone,type);
        if(success == 1){
            return new ListExcution(null, ListEnum.BINDSUCCESS);
        }else if(success == 0){
            return new ListExcution(null, ListEnum.BINDFAIL);
        }else{
            return new ListExcution(null, ListEnum.BINDISNO);
        }
    }


    @ApiOperation(value = "查询手机号")
    @PostMapping(value = "/findPhone")
    @ResponseBody
    public ListExcution<String> findPhone(Integer userId){
        String src= service.findPhone(userId);
        if(src == null){
            return new ListExcution("", ListEnum.SUCCESS);
        }else {
            return new ListExcution(src, ListEnum.SUCCESS);
        }
    }

    @ApiOperation(value = "授权登录")
    @PostMapping(value = "/login")
    @ResponseBody
    public ListExcution login(String wxNickName, String wxSex, String wxAvatar,String userType,String openId,String newOpenId){
        int success = service.login(wxNickName,wxSex,wxAvatar,userType,openId,newOpenId);
        if(success > 0){
            return new ListExcution(success, ListEnum.SUCCESS);
        }else{
            return new ListExcution(null, ListEnum.FAIL);
        }
    }

    @ApiOperation(value = "获取用户信息")
    @PostMapping(value = "/findUser")
    @ResponseBody
    public ListExcution<LoginInfo> findUser(String openId){
        LoginInfo user = service.findUser(openId);
        return new ListExcution<LoginInfo>(user,ListEnum.SUCCESS);
    }

    @ApiOperation(value = "查看用户授权后用户类型")
    @PostMapping(value = "/findUserType")
    @ResponseBody
    public ListExcution<Map> findUserType(String openId){
        Map map = service.findUserType(openId);
        return new ListExcution<Map>(map,ListEnum.SUCCESS);
    }

    @ApiOperation(value = "通过两个用户ID 获取用户信息")
    @PostMapping(value = "/findUserMsg")
    @ResponseBody
    public ListExcution<Map> findUserMsg(Integer userId,Integer userId1){
        Map map = service.findUserMsg(userId,userId1);
        return new ListExcution<Map>(map,ListEnum.SUCCESS);
    }

    @ApiOperation(value = "环信会话页面查询用户信息")
    @PostMapping(value = "/findUserMsg1")
    @ResponseBody
    public ListExcution<List<LoginInfo>> findUserMsg1(String userId){
        List<LoginInfo> info = service.findUserMsg1(userId);
        return new ListExcution<List<LoginInfo>>(info, ListEnum.SUCCESS);
    }

    @ApiOperation(value = "环信查询用户信息")
    @PostMapping(value = "/findUserMsg2")
    @ResponseBody
    public ListExcution<LoginInfo> findUserMsg2(Integer userId){
        LoginInfo info = service.findUserMsg2(userId);
        return new ListExcution<LoginInfo>(info, ListEnum.SUCCESS);
    }

    @ApiOperation(value = "注册")
    @PostMapping(value = "/newRegister")
    @ResponseBody
    public ListExcution<Void> newRegister(RegisterInfo registerInfo){
        int count = service.newRegister(registerInfo);
        if(count > 0){
            return new ListExcution<Void>(null, ListEnum.SUCCESS);
        }else if (count == -1){
            return new ListExcution<Void>(null, ListEnum.ISFAASSDSIL);
        }else if(count == -2){
            return new ListExcution<Void>(null, ListEnum.ISFAASSDSISL);
        }else{
            return new ListExcution<Void>(null, ListEnum.FAIL);
        }
    }


    @ApiOperation(value = "查是否注册过")
    @PostMapping(value = "/findRegisterIsBeing")
    @ResponseBody
    public ListExcution<Void> findRegisterIsBeing(Integer userId){
        int count = service.findRegisterIsBeing(userId);
        if(count > 0){
            return new ListExcution<Void>(null, ListEnum.FAIL);
        }else{
            return new ListExcution<Void>(null, ListEnum.SUCCESS);
        }
    }

    @ApiOperation(value = "查邀请码是否存在")
    @PostMapping(value = "/findRanCodeIsBeing")
    @ResponseBody
    public ListExcution<Void> findRanCodeIsBeing(String code){
        int count = service.findRanCodeIsBeing(code);
        if(count > 0){
            return new ListExcution<Void>(null, ListEnum.SUCCESS);
        }else{
            return new ListExcution<Void>(null, ListEnum.ISFAASSDSISL);
        }
    }


    /**
     * get请求获取String类型数据
     *
     * @param url 请求链接
     * @return
     */
    public static Map get(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        StringBuffer sb = new StringBuffer();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            System.out.println("Res:" + (entity.getContent()));
            InputStreamReader reader = new InputStreamReader(entity.getContent(), "utf-8");
            char[] charbufer;
            while (0 < reader.read(charbufer = new char[10])) {
                sb.append(charbufer);
            }
        } catch (IOException e) {//1
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
        }
        JSONObject json = new JSONObject(sb.toString());
        System.out.println(json);
        String openid = (String) json.get("openid");
        String sessionKey = (String) json.get("session_key");
        String unionid = (String) json.get("unionid");
        Map map = new HashMap();
        map.put("openId",openid);
        map.put("sessionKey",sessionKey);
        map.put("unionid",unionid);
        return map;
    }

    @ApiOperation(value = "获取openId老版")
    @PostMapping(value = "/getOpenId")
    @ResponseBody
    public Map getOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx5753938128c05c02&secret=ab9f51aa63d29282ab53ba906955609f&js_code=" + code + "&grant_type=authorization_code";
        //获取openID
        Map map = get(url);
        return map;
    }

    @ApiOperation(value = "获取openId家长端")
    @PostMapping(value = "/getOpenId1")
    @ResponseBody
    public Map getOpenId1(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxfe414ab7903ae4f8&secret=f1b5f86609324cc6048957482ef46770&js_code=" + code + "&grant_type=authorization_code";
        //获取openID
        Map map = get(url);
        return map;
    }

    @ApiOperation(value = "获取openId老师端")
    @PostMapping(value = "/getOpenId2")
    @ResponseBody
    public Map getOpenId2(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx8a7b9ecd1ce7704b&secret=a3fd9852702d3e7e363289e631a4f196&js_code=" + code + "&grant_type=authorization_code";
        //获取openID
        Map openId = get(url);
        return openId;
    }

    @ApiOperation(value = "获取unionid")
    @PostMapping(value = "/getUnionid")
    @ResponseBody
    public String getUnionid(String openId) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?appid=wxfe414ab7903ae4f8&secret=f1b5f86609324cc6048957482ef46770&grant_type=client_credential";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        StringBuffer sb = new StringBuffer();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            System.out.println("Res:" + (entity.getContent()));
            InputStreamReader reader = new InputStreamReader(entity.getContent(), "utf-8");
            char[] charbufer;
            while (0 < reader.read(charbufer = new char[10])) {
                sb.append(charbufer);
            }
        } catch (IOException e) {//1
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
        }
        JSONObject json = new JSONObject(sb.toString());
        String acessToken = (String) json.get("access_token");
        url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + acessToken + "&openid=" + openId + "&lang=zh_CN&scope=snsapi_userinfo";
        String uid = gets(url);
        return uid;
    }

    /**
     * get请求获取String类型数据
     *
     * @param url 通用请求链接
     * @return
     */
    public static String gets(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        StringBuffer sb = new StringBuffer();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            System.out.println("Res:" + (entity.getContent()));
            InputStreamReader reader = new InputStreamReader(entity.getContent(), "utf-8");
            char[] charbufer;
            while (0 < reader.read(charbufer = new char[10])) {
                sb.append(charbufer);
            }
        } catch (IOException e) {//1
            e.printStackTrace();
        } finally {
            httpGet.releaseConnection();
        }
        JSONObject json = new JSONObject(sb.toString());
        System.out.println(json);
        String unionid = (String) json.get("unionid");
        return unionid;
    }

    @ApiOperation(value = "解密手机号")
    @PostMapping(value = "/mdmdphone")
    @ResponseBody
    public String mdmdphone(String key,String iv,String encData) {
        byte[] encryptedData = Base64.decodeBase64(encData);
        byte[] ivData = Base64.decodeBase64(iv);
        byte[] session_key = Base64.decodeBase64(key);
        String a = "";
        try {
             a = AESDecodeUtils.decrypt(session_key,ivData,encryptedData);
        }catch (Exception e){
            System.out.println("出现就跪了");
        }
        return a;
    }


    @ApiOperation(value = "查邀请码")
    @PostMapping(value = "/findInvitationCode")
    @ResponseBody
    public String findInvitationCode(Integer userId) {
      return service.findInvitationCode(userId);
    }

//    @ApiOperation(value = "获取session_key")
//    @PostMapping(value = "/mdmdSessionKey")
//    @ResponseBody
//    public String mdmdSessionKey(String key,String iv,String encData) {
//        byte[] encryptedData = Base64.decodeBase64(encData);
//        byte[] ivData = Base64.decodeBase64(iv);
//        byte[] session_key = Base64.decodeBase64(key);
//        String a = "";
//        try {
//            a = AESDecodeUtils.decrypt(session_key,ivData,encryptedData);
//        }catch (Exception e){
//            System.out.println("出现就跪了");
//        }
//        return a;
//    }


    @ApiOperation(value = "MD5加密")
    @PostMapping(value = "/MD5")
    @ResponseBody
    public String md5() {
        return MD5(UUIDUtil.get32UUID());
    }

    /**
     * 对字符串md5加密(大写+数字)
     *
     * @param s 传入要加密的字符串
     * @return MD5加密后的字符串
     */

    public static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



}
